package com.xinsoft.controller.wms;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xinsoft.common.Response;
import com.xinsoft.common.exception.BDException;
import com.xinsoft.constant.Const;
import com.xinsoft.entity.dto.*;
import com.xinsoft.entity.po.ScmConsumingApplyItem;
import com.xinsoft.entity.po.ScmPushBill;
import com.xinsoft.entity.vo.ScmConsumingApplyItemDetailVo;
import com.xinsoft.entity.vo.ScmConsumingApplyPageVo;
import com.xinsoft.entity.vo.ScmConsumingApplyVo;
import com.xinsoft.service.ScmConsumingApplyItemService;
import com.xinsoft.service.ScmConsumingApplyService;
import com.xinsoft.service.ScmPushBillService;
import com.xinsoft.service.impl.SyncPushBillAdapter;
import com.xinsoft.utils.ExcelUtils;
import com.xinsoft.validator.ValidatorUtils;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 领用申请
 *
 * @folder 华德/云供应链/仓库管理/领用申请
 */
@Slf4j
@RestController
@RequestMapping("/scm/consumingApply")
public class ScmConsumingApplyController {

    @Autowired
    private ScmConsumingApplyService consumingApplyService;
    @Autowired
    private ScmConsumingApplyItemService consumingApplyItemService;
    @Autowired
    private SyncPushBillAdapter syncPushBillAdapter;
    @Autowired
    private ScmPushBillService pushBillService;


    /**
     * 分页
     */
    @PostMapping("/pageList")
    public Response<?> pageList(@RequestBody ScmConsumingApplyParam param) {
        return Response.succeed(consumingApplyService.findPageListByParam(param));
    }

    /**
     * 暂存
     */
    @PostMapping("/addOrUpdate")
    @Transactional(rollbackFor = Exception.class)
    public Response<?> addOrUpdate(@RequestBody ScmConsumingApplyDTO dto) {
        // 参数校验
        ValidatorUtils.validateEntity(dto);
        consumingApplyService.tempSave(dto);
        return Response.succeed();
    }

    /**
     * 获取详情
     */
    @GetMapping("/detail")
    public Response<ScmConsumingApplyVo> detail(@RequestParam(value = "id", defaultValue = "") Integer id) {
        return Response.succeed(consumingApplyService.detail(id));
    }

    /**
     * 删除
     */
    @PostMapping("/del")
    @Transactional(rollbackFor = Exception.class)
    public Response<?> del(@RequestBody List<Integer> ids) {
        ids = ids.stream().distinct().collect(Collectors.toList());
        consumingApplyService.del(ids);
        return Response.succeed();
    }

    /**
     * 导出
     */
    @PostMapping("/export")
    public Response<?> export(@RequestBody @ApiParam("查询参数") ScmConsumingApplyParam param, HttpServletResponse response) throws Exception {
        List<ScmConsumingApplyPageVo> list = consumingApplyService.findListByParam(param);
        ExcelUtils.exportByEasypoi(list, ScmConsumingApplyPageVo.class, "生产领用申请", "生产领用申请", response, "生产领用申请");
        return Response.succeed();
    }

    /**
     * 审核
     */
    @GetMapping("/audit")
    @Transactional(rollbackFor = Exception.class)
    public Response<?> audit(@ApiParam(value = "生产领用申请id", required = true) @RequestParam("id") Integer id) {
        consumingApplyService.audit(id);
        return Response.succeed();
    }

    /**
     * 反审核
     */
    @GetMapping("/reverseAudit")
    @Transactional(rollbackFor = Exception.class)
    public Response<?> reverseAudit(@ApiParam(value = "生产领用申请id", required = true) @RequestParam("id") Integer id) {
        consumingApplyService.reverseAudit(id);
        return Response.succeed();
    }

    /**
     * 保存并审核
     */
    @PostMapping("/saveAudit")
    @Transactional(rollbackFor = Exception.class)
    public Response<?> saveAudit(@RequestBody ScmConsumingApplyDTO dto) {
        ValidatorUtils.validateEntity(dto);
        Integer id = consumingApplyService.tempSave(dto);
        consumingApplyService.audit(id);
        return Response.succeed();
    }

    /**
     * 领用申请明细
     *
     * @param applyId    领用申请id
     * @param materialId 物料id
     * @return {@link Response}<{@link ScmConsumingApplyVo}>
     */
    @GetMapping("/applyItem")
    public Response<ScmConsumingApplyItemDetailVo> applyItem(@RequestParam(value = "applyId") Integer applyId,
                                                             @RequestParam(value = "materialId") Integer materialId,
                                                             @RequestParam(value = "sourceId") Integer sourceId) {
        return Response.succeed(consumingApplyItemService.selectApplyItem(applyId, materialId,sourceId));
    }

    /**
     * 领用出库暂存
     */
    @PostMapping("/tempSave")
    @Transactional(rollbackFor = Exception.class)
    public Response<?> tempSave(@Validated @RequestBody ScmConsumingOutstockDTO dto) {
        log.info("生产领料暂存dto：{}", JSON.toJSONString(dto));
        List<ErpOutStock> erpOutStockList = dto.getErpOutStockList();

        BigDecimal outQty = getOutQty(dto, erpOutStockList);

        // 暂存待推送单据
        List<ErpInOrOutStockParam> params = new ArrayList<>();
        erpOutStockList.forEach(erpOutStock -> {
            ErpInOrOutStockParam param = new ErpInOrOutStockParam();
            BeanUtil.copyProperties(erpOutStock, param);
            params.add(param);
        });
        ScmPushBill pushBill = new ScmPushBill();
        switch (dto.getApplyTypeId()) {
            case 10786:
                pushBill.setBillType(Const.BillType.SCLYCK);
                break;
            case 10788:
                pushBill.setBillType(Const.BillType.WWLYCK);
                break;
            case 10789:
                // pushBill.setBillType(dto.getApplyTypeId());
                break;
        }
        pushBill.setSourceId(dto.getApplyId());
        pushBill.setSourceItemId(dto.getApplyItemId());
        pushBill.setMaterialId(dto.getMaterialId());
        pushBill.setJsonParam(JSON.toJSONString(params));
        pushBillService.save(pushBill);

        // 反写领用申请已出数量
        ScmConsumingApplyItem item = consumingApplyItemService.getOne(Wrappers.lambdaUpdate(ScmConsumingApplyItem.class)
                .eq(ScmConsumingApplyItem::getId, dto.getApplyItemId())
                .eq(ScmConsumingApplyItem::getApplyId, dto.getApplyId())
                .eq(ScmConsumingApplyItem::getMaterialId, dto.getMaterialId()));
        item.setOutNum(item.getOutNum().add(outQty));
        consumingApplyItemService.updateById(item);
        return Response.succeed();
    }

    public BigDecimal getOutQty(ScmConsumingOutstockDTO dto, List<ErpOutStock> erpOutStockList) {
        ScmConsumingApplyItem applyItem = consumingApplyItemService.getById(dto.getApplyItemId());
        long count = erpOutStockList.stream().filter(o -> !Objects.equals(o.getMaterialId(), applyItem.getMaterialId())).count();
        if (count > 0) {
            throw new BDException("物料错误，请扫描正确的物料码");
        }
        long count1 = erpOutStockList.stream().filter(item -> item.getQty().compareTo(BigDecimal.ZERO) <= 0).count();
        if (count1 > 0) {
            throw new BDException("出库数量必须大于0");
        }
        BigDecimal notOutQty = applyItem.getConsumingNum().subtract(applyItem.getOutNum());
        BigDecimal outQty = erpOutStockList.stream().map(ErpOutStock::getQty).reduce(BigDecimal.ZERO, BigDecimal::add);
        if (outQty.compareTo(notOutQty) > 0) {
            throw new BDException("出库数量超出待出库数量");
        }
        return outQty;
    }

    /**
     * 领用出库直接提交
     */
    @PostMapping("/outstock")
    @Transactional(rollbackFor = Exception.class)
    public Response<?> outstock(@Validated @RequestBody ScmConsumingOutstockDTO dto) {
        log.info("生产领料直接提交dto：{}", JSON.toJSONString(dto));
        List<ErpOutStock> erpOutStockList = dto.getErpOutStockList();

        BigDecimal outQty = getOutQty(dto, erpOutStockList);

        // 调用金蝶出库
        List<ErpInOrOutStockParam> params = new ArrayList<>();
        erpOutStockList.forEach(erpOutStock -> {
            ErpInOrOutStockParam param = new ErpInOrOutStockParam();
            BeanUtil.copyProperties(erpOutStock, param);
            params.add(param);
        });
        Response<?> response = Response.succeed();
        switch (dto.getApplyTypeId()) {
            case 10786:
                response = syncPushBillAdapter.feedingOutStock(params);
                break;
            case 10788:
                response = syncPushBillAdapter.sourcingFeedingOutStock(params);
                break;
            case 10789:
                response = syncPushBillAdapter.otherOutStock(params);
                break;
        }
        // 反写领用申请已出数量
        consumingApplyItemService.update(Wrappers.lambdaUpdate(ScmConsumingApplyItem.class)
                .eq(ScmConsumingApplyItem::getId, dto.getApplyItemId())
                .eq(ScmConsumingApplyItem::getApplyId, dto.getApplyId())
                .eq(ScmConsumingApplyItem::getMaterialId, dto.getMaterialId())
                .set(ScmConsumingApplyItem::getOutNum, outQty));

        return response;
    }
}
